<template>
  <a-table
    :scroll="tableScroll"
    :style="{ width: '100%' }"
    :loading="loading"
    :columns="tableColumns"
    :data-source="dataList"
    :pagination="false"
    class="header-right-angle admin-table"
  >
    <template #headerCell="{ column }">
      <template v-if="column.dataIndex === 'authType'">
        <dropdown-select v-model:value="pageForm.authType" :options="authTypeOptions" @select="getDataList(pageForm)" />
      </template>
      <template v-if="column.dataIndex === 'num'"> {{ pageForm.authType === 1 ? '序列号' : 'LicenseID' }}</template>

      <template v-else-if="column.dataIndex === 'openNum'">
        <div v-if="pageForm.authType === 1">已激活/可激活设备数</div>
        <div v-else-if="pageForm.authType === 2">可激活设备数</div></template
      >
    </template>
    <template #bodyCell="{ column, record }">
      <template v-if="column.dataIndex == 'status'">
        {{ record.status }}
      </template>
      <template v-else-if="column.dataIndex == 'openNum'">
        <div v-if="record.authType === 1">{{ record.usedActivateNum }}/{{ record.totalActivateNum }}</div>
        <div v-else-if="record.authType === 2">{{ record.totalActivateNum }}</div>
      </template>
      <template v-else-if="column.dataIndex == 'authType'">
        {{ authTypeObj[record.authType as AuthType] }}
      </template>
      <template v-else-if="column.dataIndex == 'tools'">
        <a-space>
          <a-button type="link" @click="handleOpenDeviceCodeModal(record.id)">设备码</a-button>
          <a-button v-if="isAdmin && checkKey('user-list-sdk-download')" type="link" @click="downloadSdk(record.operateMethodId)"
            >下载</a-button
          >
          <a-button v-else-if="!isAdmin && checkKey('student-list-sdk-download')" type="link" @click="downloadSdk(record.operateMethodId)"
            >下载</a-button
          >
        </a-space>
      </template>
      <template v-else>
        {{ replaceEmptyStr(record[column.dataIndex as string]) }}
      </template>
    </template>
  </a-table>
  <device-code ref="deviceCodeRef" />
</template>

<script lang="ts" setup>
  import { message } from 'ant-design-vue'
  import { debounce } from 'g6-fn'
  import { computed, inject, ref } from 'vue'
  import { useRequest } from 'vue-request'

  import DropdownSelect from '@/components/DropdownSelect/index.vue'
  import manualMessage from '@/components/ManualMessage/index'
  import { checkKey } from '@/directives/auth'
  import { clientApi, fetchDownload } from '@/services/api'
  import { replaceEmptyStr } from '@/utils'
  import { filterTableColumns } from '@/utils/index'

  import { AuthType, authTypeObj } from '../../../config'
  import DeviceCode from '../device-code.vue'
  export interface SdkItem {
    /**
     * 算法名称
     */
    algoName: string
    /**
     * AuditId
     */
    auditId: string
    /**
     * 授权时间
     */
    authTime: string
    /**
     * 激活方式：1：联网2离线
     */
    authType: number
    /**
     * 激活方式名称
     */
    authTypeName: string
    /**
     * AppServeId
     */
    id: string
    /**
     * 语言
     */
    language: string
    /**
     * 序列号 | licenseID
     */
    num: string
    /**
     * 算法id
     */
    operateMethodId: string
    /**
     * 算法情况
     */
    operateMethodStatus: string
    /**
     * 平台
     */
    platform: string
    /**
     * 调用总量
     */
    totalActivateNum: number
    /**
     * 使用量
     */
    usedActivateNum: number
    /**
     * 版本号
     */
    version: string
  }

  // 表格
  const tableColumns = ref(
    filterTableColumns([
      {
        title: '算法服务',
        dataIndex: 'algoName',
        width: 140
      },
      {
        title: '版本号',
        dataIndex: 'version',
        width: 100
      },
      {
        title: '平台',
        dataIndex: 'platform',
        width: 180
      },
      {
        title: '语言',
        dataIndex: 'language',
        width: 100
      },
      {
        title: '联网激活',
        dataIndex: 'authType',
        width: 140
      },
      {
        title: '序列号',
        dataIndex: 'num',
        width: 200
      },
      {
        title: '已激活/可激活设备数',
        dataIndex: 'openNum',
        width: 180
      },
      {
        title: '授权时间',
        dataIndex: 'authTime',
        width: 190
      },
      {
        title: '',
        dataIndex: 'tools',
        width: 140,
        fixed: 'right'
      }
    ])
  )
  const tableScroll = computed(() => {
    const scrollX = tableColumns.value.reduce((prev, curr) => {
      return prev + (curr.width as number)
    }, 0)
    return {
      x: scrollX > 1022 ? scrollX : undefined,
      y: dataList.value.length >= 9 ? 510 : undefined
    }
  })

  const clientId = inject('clientId')
  const isAdmin = inject('isAdmin')

  const pageForm = ref({
    uid: clientId,
    authType: 1
  })

  const authTypeOptions = [
    { label: '联网激活', value: 1 },
    { label: '离线激活', value: 2 }
  ]

  const { data, loading, runAsync: getDataList } = useRequest<any>(clientApi.sdkList)

  const dataList = computed<SdkItem[]>(() => {
    if (!data.value?.data) {
      return []
    }
    return data.value?.data
  })

  const downloadSdk = debounce(async (id: string): Promise<void> => {
    manualMessage.loading('数据准备中,请耐心等待...', 0)
    try {
      const { data } = await clientApi.downloadSdk(id)(
        {},
        {
          isResponseAll: true,
          timeout: 300000 //设置超时时长5min
        }
      )
      await fetchDownload(data.data.fileUrl, data.data.fileName)
      manualMessage.destroy()
      await message.success({ content: '文件下载成功', key: 'downloading', duration: 2 })
    } catch (error) {
      manualMessage.destroy()
      message.error({ content: '文件下载失败', key: 'downloading', duration: 2 })
    }
  }, 500)
  const deviceCodeRef = ref<InstanceType<typeof DeviceCode>>()
  const handleOpenDeviceCodeModal = async (id: string) => {
    try {
      deviceCodeRef.value?.openModal()
      deviceCodeRef.value?.changeLoading(true)
      const { data } = await clientApi.getLicDeviceCode(id)()
      deviceCodeRef.value?.changeLoading(false)
      deviceCodeRef.value?.setDetailInfo(data)
      console.log('handleOpenDeviceCodeModal', data)
    } catch (error) {
      deviceCodeRef.value?.changeLoading(false)
    }
  }
  getDataList(pageForm.value)
</script>
